package com.zhoug.common3.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Build;

import com.zhoug.common3.Logger;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import androidx.annotation.NonNull;

/**
 * apk工具,
 * 对apk文件安全校验
 * @Author 35574
 * @Date 2021/8/31
 * @Description
 */

public class ApkUtils {
    private static final String TAG = ">>>ApkUtils";
    private static  boolean debug=true;
    protected static char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static void setDebug(boolean debug) {
        ApkUtils.debug = debug;
    }

    /**
     * 检查本app应用的签名是否合法
     * @param context
     * @param signatureAfterMd5 正确的签名SHA1经过md5编码后的字符串,为null是返回true,不进行签名校验
     * @return 签名校验结果
     */
    public static boolean checkSignature(Context context,String signatureAfterMd5){
        if(signatureAfterMd5==null)return true;
        Signature[] apkSignatures = getApkSignatures(context);
        if(apkSignatures!=null && apkSignatures.length>0){
            Signature apkSignature = apkSignatures[0];
            if(apkSignature!=null){
                String md5 = MD5Utils.getMD5(getSignatureSha1(apkSignature));
                return signatureAfterMd5.equalsIgnoreCase(md5);
            }
        }
        return false;
    }

    /**
     * 获取本应用的签名
     * @param context
     */
    public static Signature[] getApkSignatures(@NonNull Context context) {
        try {
            String packageName = context.getPackageName();
            if (debug) {
                Logger.d(TAG, "getApkSignature:packageName="+packageName);
            }
            Signature[] signatures;
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.P){
                PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES);
                signatures = packageInfo.signingInfo.getApkContentsSigners();
            }else{
                PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
                signatures = packageInfo.signatures;
            }
            return signatures;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取签名的SHA1
     * @param signature
     * @return
     */
    public static String getSignatureSha1( Signature signature) {
        if(signature==null) return null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(signature.toByteArray()));
            //加密算法的类，这里的参数可以使 MD4,MD5 等加密算法
            MessageDigest md = MessageDigest.getInstance("SHA1");
            //获得公钥
            byte[] publicKey = md.digest(cert.getEncoded());
            //字节到十六进制的格式转换
            String hexString = byte2HexFormatted(publicKey);
            if (debug) {
                Logger.d(TAG, "getSignatureSha1:" + hexString);
            }
            return hexString;
        } catch (CertificateException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 二行制转字符串 用":"分割
     * 这里是将获取到得编码进行16进制转换
     * @param arr
     * @return
     */
    private static String byte2HexFormatted(byte[] arr) {
        StringBuilder str = new StringBuilder(arr.length * 2);
        for (int i = 0; i < arr.length; i++) {
            String h = Integer.toHexString(arr[i]);
            int len = h.length();
            if (len == 1)
                h = "0" + h;
            if (len > 2)
                h = h.substring(len - 2, len);//00af取最后2位
            str.append(h.toUpperCase());
            if (i < (arr.length - 1))
                str.append(':');
        }
        return str.toString();
    }

    /**
     * 获取文件的sha1值
     *
     * @param apkPath
     * @return
     */
    public static String getFileSha1(String apkPath) {
        return getFileSha1(new File(apkPath));
    }



    /**
     * 复制内容到剪贴板
     * @param context
     * @param label
     * @param content
     */
    public void copyContentToClipboard(@NonNull Context context,String label,String content) {
        if(label==null){
            label="label";
        }
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText(label, content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }


    //注意不能用new BigInteger(1, md.digest()).toString(16); 原因是bigint进行16进制转换的时候第一个0被自动去掉了
    /**
     * 获取文件的sha1值
     *
     * @param apkPath
     * @return
     */
    public static String getFileSha1(File apkPath) {
        byte[] digest = null;
        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] bytes = new byte[1024];
            int byteCount;
            fis = new FileInputStream(apkPath);
            while ((byteCount = fis.read(bytes)) > 0) {
                md.update(bytes, 0, byteCount);
            }
            digest = md.digest();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bufferToHex(digest);
    }

    /**
     * 字节数组转化成16进制字符串
     * @param bytes
     * @return
     */
    private static String bufferToHex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) return null;
        return bufferToHex(bytes, 0, bytes.length);
    }

    /**
     * 字节数组转化成16进制字符串
     * @param bytes
     * @param start 开始位置
     * @param length 需要转换的长度
     * @return
     */
    private static String bufferToHex(byte[] bytes, int start, int length) {
        if (bytes == null || bytes.length == 0) return null;
        StringBuffer stringbuffer = new StringBuffer(2 * length);
        int end = start + length;
        for (int l = start; l < end; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = HEX_DIGITS[(bt & 0xf0) >> 4];
        char c1 = HEX_DIGITS[bt & 0xf];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }

}
